using AjaxControlToolkit;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Reflection;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace AspAlliance.SimpleCms
{
    class AdminPage : CmsPageBase
    {
        private const string setupQS = "setupdb";
        private const string toggleQS = "toggle";
        private List<CmsPage> allPages = null;
        private HtmlHead pageHead;
        private Panel header;
        private HtmlGenericControl pageBody;
        private HtmlForm myForm;
        private ScriptManager myManager;
        private Table pagesTable;
        private Panel myiFramePanel;
        private bool databaseError = false;
        private DataHelper _dataHelper;

        public AdminPage()
        {
            _dataHelper = new DataHelper(CmsSettings.StaticConnectionString);
        }

        protected override void OnPreInit(EventArgs e)
        {
            base.OnPreInit(e);
            
            if (CmsConfig != null)
            {
                this.AppRelativeVirtualPath = CmsConfig.AdminPage;
            }
            else
            {
                return;
            }

            try
            {
                allPages = CmsPage.SelectAll();
            }
            catch (SqlException)
            {
                databaseError = true;
                return;
            }



            pageHead = new HtmlHead();
            pageHead.Title = "Administration Page";

            HtmlLink cssLink = new HtmlLink();
            cssLink.Href = ClientScript.GetWebResourceUrl(this.GetType(), "AspAlliance.SimpleCms.styles.css");
            cssLink.Attributes.Add("rel", "stylesheet");
            cssLink.Attributes.Add("type", "text/css");

            pageHead.Controls.Add(cssLink);
            pageHead.Controls.Add(GetJavaScript());

            pageBody = new HtmlGenericControl("body");

            myForm = new HtmlForm();
            myForm.ID = "frm";

            CreateHeader();

            myManager = new ScriptManager();
            myManager.EnablePartialRendering = true;
            myManager.ID = "sm1";

            myiFramePanel = new Panel();
            myiFramePanel.ID = "iframepanel";

            if (allPages != null)
            {
                BuildCmsPageTable(allPages);
            }

            Panel newPageBottom = new Panel();
            newPageBottom.CssClass = "newPageBottom";
            newPageBottom.Style.Add("background", "url('" + ClientScript.GetWebResourceUrl(this.GetType(), "AspAlliance.SimpleCms.Images.newdoc.gif") + "') no-repeat 2px");

            HyperLink botNewPage = new HyperLink();
            botNewPage.Text = "Create New Page";
            botNewPage.NavigateUrl = CmsConfig.EditPage;

            newPageBottom.Controls.Add(botNewPage);

            myForm.Controls.Add(myManager);
            myForm.Controls.Add(header);
            myForm.Controls.Add(pagesTable);
            myForm.Controls.Add(newPageBottom);
            myForm.Controls.Add(GetVersionInfo());
            myForm.Controls.Add(myiFramePanel);

            pageBody.Controls.Add(myForm);
            this.Controls.Add(pageHead);
            this.Controls.Add(pageBody);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            if (this.Request.QueryString[setupQS] != null && this.Request.QueryString[setupQS] == "1")
            {
                _dataHelper.SetupTable();
                this.Response.Redirect(CmsConfig.AdminPage);
            }

            if (this.Request.QueryString[toggleQS] != null && this.Request.QueryString[toggleQS] != string.Empty)
            {
                CmsPage.ToggleStatus(this.Request.QueryString[toggleQS], this);

                this.Response.Redirect(CmsConfig.AdminPage);
            }
        }

        protected void RenderConfigError(HtmlTextWriter writer)
        {
            RenderBeginning(writer, "Administrative Page", "", "");

            writer.WriteLine("<div><h1>Simple CMS was unable to find all or part of its custom configuration settings.</h1></div><br />");

            writer.WriteLine("<div>Please verify that the Simple CMS configurations are in your configuration file. The following is an example of the sections Simple CMS needs, which should be in your configuration file. This needs to be customized before it is placed in your configuration file. If a section all ready exists in your configuration file then just add the child content from these.</div><br />");

            writer.WriteLine(@"<div>
                &lt;configSections&gt;<br />
		        &lt;section name=&quot;cmsConfig&quot; type=&quot;AspAlliance.SimpleCms.CmsConfigSectionHandler, AspAlliance.SimpleCms&quot;/&gt;<br />
	            &lt;/configSections&gt;<br />
                </div><br />");

            writer.WriteLine(@"<div>
                &lt;connectionStrings&gt;<br />
		        &lt;add name=&quot;CmsDb&quot; connectionString=&quot;Data Source=localhost;Initial Catalog=SimpleCms;uid=CmsUser;pwd=SimpleCms;&quot; providerName=&quot;System.Data.SqlClient&quot;/&gt;<br />
	            &lt;/connectionStrings&gt;</div><br />");

            writer.WriteLine(@"<div> 
                &lt;system.web&gt;<br />
                &lt;httpHandlers&gt;<br />
                &lt;add verb=&quot;*&quot; path=&quot;CMS/*.aspx&quot; type=&quot;AspAlliance.SimpleCms.CmsPageFactory&quot;/&gt;<br />
                &lt;add verb=&quot;*&quot; path=&quot;*.cmsx&quot; type=&quot;AspAlliance.SimpleCms.CmsPageFactory&quot;/&gt;<br />
                &lt;/httpHandlers&gt;<br />
                &lt;/system.web&gt;<br />
                </div><br />");

            writer.WriteLine(@"<div> 
                &lt;cmsConfig <br />
                    connectionStringName=&quot;CmsDb&quot; <br />
                    masterPage=&quot;MasterPage.master&quot; <br />
                    adminPage=&quot;~/admin.cmsx&quot; <br />
                    editPage=&quot;~/edit.cmsx&quot; <br />
                    defaultFileExtension=&quot;.cmsx&quot; /&gt; </div><br />");

            RenderEnd(writer);
        }

        protected LiteralControl GetJavaScript()
        {
            LiteralControl myJavaScript = new LiteralControl(@"
                    <script type='text/javascript'>
                    <!--
                        function DisablePage(url)
                        {
                            window.location='" + ResolveUrl(CmsConfig.AdminPage) + @"?toggle=' + url;
                        }
                        function EnablePage(url)
                        {
                            window.location='" + ResolveUrl(CmsConfig.AdminPage) + @"?toggle=' + url;
                        }
                        function SetupDB(pageId)
                        {
                            window.location='" + ResolveUrl(CmsConfig.AdminPage) + @"?setupdb=1';
                        }
                        
                    //-->
                    </script>");
            return myJavaScript;
        }

        protected LiteralControl GetVersionInfo()
        {
            string version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
            string copyright = string.Empty;
            object[] customs = Assembly.GetExecutingAssembly().GetCustomAttributes(false);
            foreach (object eachAttribute in customs)
            {
                if (eachAttribute.GetType() == typeof(AssemblyCopyrightAttribute))
                {
                    AssemblyCopyrightAttribute copyobject = eachAttribute as AssemblyCopyrightAttribute;
                    copyright = copyobject.Copyright;
                }
            }

            return new LiteralControl(@"<div align='center' class='copyright'><strong>Simple CMS</strong> Version " + version + " " + copyright + "</div>");
        }

        protected void CreateHeader()
        {
            header = new Panel();
            header.CssClass = "header";
            header.Style.Add("background", "#910000 url('" + ClientScript.GetWebResourceUrl(this.GetType(), "AspAlliance.SimpleCms.Images.header-bkgd.gif") + "') bottom");

            Panel headerTitle = new Panel();
            headerTitle.CssClass = "headerTitle";

            headerTitle.Controls.Add(new LiteralControl("Simple CMS v" + Assembly.GetExecutingAssembly().GetName().Version.ToString()));

            Panel newPage = new Panel();
            newPage.CssClass = "newPage";
            newPage.Style.Add("background", "url('" + ClientScript.GetWebResourceUrl(this.GetType(), "AspAlliance.SimpleCms.Images.newdoc.gif") + "') no-repeat");

            HyperLink topNewPage = new HyperLink();
            topNewPage.Text = "Create New Page";
            topNewPage.NavigateUrl = CmsConfig.EditPage;

            newPage.Controls.Add(topNewPage);

            header.Controls.Add(headerTitle);
            header.Controls.Add(newPage);
        }

        protected void RenderSqlException(HtmlTextWriter writer)
        {
            writer.WriteLine("<div><h1>Simple CMS cannot establish a connection to the Database.</h1></div><br />");

            writer.WriteLine("<div>Please make sure that the information specified in the connection string section of the configuration file is correct. Below is an example (this example needs to be customized)</div><br />");

            writer.WriteLine(@"<div>
                    &lt;connectionStrings&gt;<br />
		            &lt;add name=&quot;CmsDb&quot; connectionString=&quot;Data Source=localhost;Initial Catalog=SimpleCms;uid=CmsUser;pwd=SimpleCms;&quot; providerName=&quot;System.Data.SqlClient&quot;/&gt;<br />
	                &lt;/connectionStrings&gt;</div><br />");

            writer.WriteLine("<div>Click the 'Setup Database' button to configure the database using the connection string specified in your configuration file. You MUST have a working connection string to a database with a login account which has access to create the required table. This account will also need permission to perform standard SQL commands on the database. Make sure that the ASP.NET account also has access to select from the database, or users will not be able to view these pages you create.</div><br />");

            writer.WriteLine("<input type='button' value='Setup Database' onclick='SetupDB()' />");
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (CmsConfig == null || CmsConfig.AdminPage == null || CmsConfig.ConnectionString == null)
            {
                RenderConfigError(writer);
            }
            else
            {

                writer.RenderBeginTag(HtmlTextWriterTag.Html);

                if (databaseError)
                {
                    GetJavaScript().RenderControl(writer);
                    RenderSqlException(writer);
                }

                base.Render(writer);

                writer.RenderEndTag(); // </html>
            }
        }

        protected void BuildCmsPageTable(List<CmsPage> pageData)
        {

            pagesTable = TableHelper.CreateTable();
            pagesTable.CssClass = "pagetable";
            pagesTable.Width = new Unit("100%");

            //Table Header
            TableRow mainHeadingRow = new TableRow();
            pagesTable.Rows.Add(mainHeadingRow);

            TableCell mainHeading;

            mainHeading = TableHelper.AddHeaderCell(mainHeadingRow, "<h3><b>Managed Pages</b></h3>");
            mainHeading.ColumnSpan = 4;
            mainHeading.CssClass = "tablehead";

            TableRow secondaryHeadingRow = new TableRow();
            secondaryHeadingRow.CssClass = "tablesubhead";
            pagesTable.Rows.Add(secondaryHeadingRow);

            // add second row headings
            TableHelper.AddHeaderCell(secondaryHeadingRow, "Edit Page");
            TableHelper.AddHeaderCell(secondaryHeadingRow, "Status");
            TableHelper.AddHeaderCell(secondaryHeadingRow, "Page Title (Click to view)");
            TableHelper.AddHeaderCell(secondaryHeadingRow, "File Path/Name");            

            TableRow pageRow;
            int alternator = 0;

            foreach (CmsPage myPage in pageData)
            {
                pageRow = new TableRow();
                if (alternator % 2 == 0)
                {
                    pageRow.CssClass = "tablerow";
                }
                else
                {
                    pageRow.CssClass = "tablealtrow";
                }
                ++alternator;

                

                // Edit Column
                TableCell editCell = new TableCell();

                string editImageUrl = this.ClientScript.GetWebResourceUrl(this.GetType(), "AspAlliance.SimpleCms.Images.editgrid.gif");
                HtmlAnchor editLink = new HtmlAnchor();
                editLink.InnerHtml = "<img src='" + editImageUrl + "' alt='Edit Page' border='0' />";
                editLink.HRef = ResolveClientUrl(CmsConfig.EditPage) + "?" + Resources.PageIdQueryString + "=" + myPage.Id;

                editCell.Controls.Add(editLink);

                pageRow.Cells.Add(editCell);

                // Status Column
                if ((bool)myPage.Enabled == true)
                {
                    string imageUrl = this.ClientScript.GetWebResourceUrl(this.GetType(), "AspAlliance.SimpleCms.Images.enabled.gif");
                    TableHelper.AddCell(pageRow, "<img src='" + imageUrl + "' alt='Click to disable' onclick='DisablePage(\"" + myPage.Url + "\")' />");
                }
                else
                {
                    string imageUrl = this.ClientScript.GetWebResourceUrl(this.GetType(), "AspAlliance.SimpleCms.Images.disabled.gif");
                    TableHelper.AddCell(pageRow, "<img src='" + imageUrl + "' alt='Click to enable' onclick='EnablePage(\"" + myPage.Url + "\")' />");
                }

                // Title Column
                if ((bool)myPage.Enabled == true)
                {
                    TableHelper.AddCell(pageRow, myPage.Title, myPage.Url);
                }
                else
                {
                    TableHelper.AddCell(pageRow, myPage.Title);
                }

                // URL Column
                if ((bool)myPage.Enabled == true)
                {
                    TableHelper.AddCell(pageRow, myPage.Url, myPage.Url);
                }
                else
                {
                    TableHelper.AddCell(pageRow, myPage.Url);
                }

                pagesTable.Rows.Add(pageRow);
            }

        }
    }
}
